package com.hourse.app.service.impl;

import com.hourse.app.entity.TickerEntity;
import com.hourse.app.service.TickerService;
import com.hourse.app.vo.rms.TickerRetVo;
import com.hourse.platform.exception.AppException;
import com.hourse.platform.service.impl.PublicServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.List;

/**
 * @作者：lichenguang
 * @描述：【货币】
 * @创建：2021/12/25 20:28
 */
@Service
@Slf4j
public class TickerServiceImpl extends PublicServiceImpl implements TickerService {

  @Resource
  private TaskExecutor taskExecutor;


  /**
   * @描述：【获取所有的币种信息】
   * @作者：lichenguang
   * @时间: 2022/1/17 20:33
   */
  @Override
  @Transactional(propagation = Propagation.REQUIRED)
  public List<TickerEntity> allTicker(String bourseTag, String currency) throws AppException {

    //CurrencyKindEntity currencyKindEntity = currencyKindService.byCode(currency);
    //List<TickerEntity> list = (List<TickerEntity>) PlatformFactory.getPlatform(bourseTag).allTicker(currencyKindEntity);


    // TODO 查询币种入库数据，后续可能为推送至管道，其他成功处理管道中的数据进行存储操作
    // TODO 测试避免太多数据入库，暂时注释信息插入数据
    //try {
    //  // 币种信息数据异步插入数据库
    //  this.asynBatchSave(tickers);
    //} catch (Exception e) {
    //  log.info("批量插入币种信息异常");
    //  e.printStackTrace();
    //}

    //return list;
    return null;
  }

  /**
   * @描述：【异步存储货币行情信息】
   * @作者：lichenguang
   * @时间: 2022/1/17 20:34
   */
  @Override
  public void asynBatchSave(List<TickerEntity> list) {

    taskExecutor.execute(new Runnable() {
      @Override
      public void run() {
        System.out.println("开始执行币种信息存储任务!");
        try {
          //模拟耗时操作
          baseDao.batchsaveOrUpdateObject(list);
        } catch (Exception e) {
          e.printStackTrace();
        }
        log.info("币种信息任务结束完毕!");
      }
    });

  }

  @Override
  public Object headerTicker() throws AppException, CloneNotSupportedException, InvalidKeyException, UnsupportedEncodingException {
    ArrayList<TickerRetVo> retList = new ArrayList<>();

    //// 获取所有热门币种
    //List<CurrencyHotEntity> list = tickerHodService.HodCurrency();
    //for (CurrencyHotEntity currencyHotEntity : list) {
    //
    //  CurrencyKindEntity currencyKindEntity = currencyKindService.findById(currencyHotEntity.getCKId());
    //  String platform = currencyHotEntity.getPlatform();
    //  TickerRetVo vo = (TickerRetVo) PlatformFactory.getPlatform(platform).ticker(currencyKindEntity);
    //  vo.setMarket(currencyKindEntity.getCode());
    //  vo.setPlatform(currencyHotEntity.getPlatform());
    //  retList.add(vo);


      //switch (currencyHotEntity.getPlatform()) {
      //  case "zbCode":
      //    code = currencyKindEntity.getZbCode();
      //    if (StringTools.isNotNull(code)) {
      //      JSONObject retJson = ZbRequestTool.ticker(code);
      //      JSONObject ticker = JSONObject.parseObject(String.valueOf(retJson.get("ticker")));
      //      tickerEntity = JSONObject.toJavaObject(ticker, TickerEntity.class);
      //      tickerEntity.setMarket(currencyKindEntity.getCode().toUpperCase());
      //      tickerEntity.setId(currencyKindEntity.getId());
      //      retList.add(tickerEntity);
      //    }
      //    break;
      //case "oyCode":
      //code = currencyKindEntity.getOyCode();
      //if (StringTools.isNotNull(code)) {
      //  //JSONObject retJson = OkexRequesTools.ticker(code);
      //  JSONArray data = retJson.getJSONArray("data");
      //  for (Object datum : data) {
      //    JSONObject item = (JSONObject) datum;
      //    tickerEntity.setHigh(item.getString("high24h"));
      //    tickerEntity.setLow(item.getString("low24h"));
      //    tickerEntity.setBuy(item.getString("bidPx"));
      //    tickerEntity.setSell(item.getString("askPx"));
      //    tickerEntity.setLast(item.getString("last"));
      //    tickerEntity.setOpen(item.getString("open24h"));
      //    tickerEntity.setVol(item.getString("volCcy24h"));
      //    tickerEntity.setTs(item.getString("ts"));
      //    tickerEntity.setMarket(currencyKindEntity.getCode().toUpperCase());
      //    tickerEntity.setId(currencyKindEntity.getId());
      //    retList.add(tickerEntity);
      //  }

      //}
      //break;
      //default:
      //  throw new AppException("平台Code异常");
      //}
    //}

    return retList;
  }


  //  * @param market String	例：btc_qc
  //* @param type   String	1min/3min/5min/15min/30min/1day/3day/1week/1hour/2hour/4hour/6hour/12hour
  //* @param since  long	从这个时间戳之后的
  //* @param size   int	返回数据的条数限制（默认为1000，如果返回数据多于1000条，那么只返回1000条）
  @Override
  @Transactional(propagation = Propagation.REQUIRED)
  public Object selectK(String market, String type, String platform, long since, int size) throws AppException {
    //
    //CurrencyKindEntity entity = currencyKindService.byCode(market);
    //
    //JSONObject resJson = (JSONObject) PlatformFactory.getPlatform(platform).getK(entity, type, since, size);

    //switch (platform) {
    //  case BourseTagConstant.ZB_PLATFORM:
    //    resJson = ZbRequestTool.market(entity.getZbCode(), type, since, size);
    //    break;
    //  case BourseTagConstant.OKEX_PLATFORM:
    //    type = this.joinOkexKType(type);
    //    resJson = OkexRequesTools.market(entity.getOyCode(), type);
    //    break;
    //  default:
    //    throw new AppException("暂不支持该三方平台");
    //}

    //JSONArray jsonArray = resJson.getJSONArray("data");

    //return jsonArray;
    return null;
  }

  /**
   * @描述：【获取单个货币行情】
   * @作者：lichenguang
   * @时间: 2022/1/21 17:44
   */
  @Override
  public Object ticker(String market, String platform) throws AppException {

    //CurrencyKindEntity currencyKindEntity = currencyKindService.byCode(market);
    //if (currencyKindEntity == null) {
    //  throw new AppException("未查询到对应币种信息");
    //}
    //
    //Object ticker = PlatformFactory.getPlatform(platform).ticker(currencyKindEntity);
    //
    //return ticker;

    return null;
    //CurrencyKindEntity currencyKindEntity = currencyKindService.byCode(market);
    //JSONObject resJson;
    //TickerRetVo tickerRetVo;
    //JSONObject item;
    //switch (platform) {
    //    //  case BourseTagConstant.ZB_PLATFORM:
    //    //    resJson = ZbRequestTool.ticker(currencyKindEntity.getZbCode());
    //    //    item = resJson.getJSONObject("ticker");
    //    //    tickerRetVo = new TickerRetVo(item.getString("last"), item.getString("riseRate"),
    //    //      item.getString("high"), item.getString("low"), item.getString("vol"));
    //    //    break;
    //    //  case BourseTagConstant.OKEX_PLATFORM:
    //    //    resJson = OkexRequesTools.ticker(currencyKindEntity.getOyCode());
    //    //    JSONArray datas = resJson.getJSONArray("data");
    //    //    item = (JSONObject) datas.get(0);
    //    //    tickerRetVo = new TickerRetVo(item.getString("last"), "", item.getString("high24h"),
    //    //      item.getString("low24h"), item.getString("volCcy24h"));
    //    //    break;
    //    //  default:
    //    //    throw new AppException("暂不支持该三方平台");
    //    //}
    // TODO 后续读取库中内容，目前根据传入的货币去查询三方，会出现货币不存在异常，所以处理返回为NULL
    //if (StringTools.isNull(resJson.getString("error"))) {
    //  return tickerRetVo;
    //} else {
    //  log.info("获取单个货币行情异常");
    //  return null;
    //}

  }

  /**
   * @描述：【获取历史交易记录】
   * @作者：lichenguang
   * @时间: 2022/1/21 17:44
   */
  @Override
  public Object trades(String currency, String platform) throws AppException, IOException {
    //CurrencyKindEntity currencyKindEntity = currencyKindService.byCode(currency);
    //
    //HashMap<String, List<TradesRetVo>> map = (HashMap<String, List<TradesRetVo>>) PlatformFactory.getPlatform(platform).trades(currencyKindEntity);
    //
    //return map;
    return null;
  }

  /**
   * @描述：【处理欧易K线图类型】
   * @作者：lichenguang
   * @时间: 2022/1/18 0:23
   */
  //private String joinOkexKType(String type) {
  //  switch (type) {
  //    case "1min":
  //      type = "1m";
  //      break;
  //    case "1hour":
  //      type = "1H";
  //      break;
  //    case "1day":
  //      type = "1D";
  //      break;
  //    case "1week":
  //      type = "1Wutc";
  //      break;
  //  }
  //
  //  return type;
  //}

}
















